package com.gwtapps.messenger.client.view;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MouseListenerAdapter;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.gwtapps.messenger.client.model.Contact;
import com.gwtapps.messenger.client.model.Message;

// the mapView looks like ContactListView
public class MapView extends Composite{
	
	public Map<String, Character> allCharacters = new HashMap<String, Character>();
	
	MessengerView view;
	
	int mainGameWindowSizeWidth=640;		//game window size W
	int mainGameWindowSizeHeight=480;		//game window size H
	
	private AbsolutePanel map=new AbsolutePanel();				// Permits abs. pos. of widgets
	private AbsolutePanel mapContaierPan=new AbsolutePanel();	// Permits abs. pos. of widgets
	private FocusPanel focPan=new FocusPanel();				// Permits mouse event capture
	
	private Image grid=new Image("./MSEF000.gif");
	
	private int mapPositionX=0;				// Map position X
	private int mapPositionY=0;				// Map position Y
	
	private int mouseOnMapPositionX=0;		// Mouse position on map X
	private int mouseOnMapPositionY=0;		// Mouse position on map Y
	
	/*Move Map's Booleans if one of them is true map will move to its direction*/
	private boolean mapMoveRight=false;
	private boolean mapMoveLeft=false;
	private boolean mapMoveUp=false;
	private boolean mapMoveDown=false;
	
	int lenghtOfTileOnXDirection=40;
	int lenghtOfTileOnYDirection=30;
	
	int startX=lenghtOfTileOnXDirection*48;				//start position of creation of tiles   X/ size * 48  EX: 48*20=960 ,20 tiles in x direction*/
	int startY=0;
	
	@SuppressWarnings("deprecation")
	public MapView(final MessengerView view) {

		this.view = view;
		mapContaierPan.setPixelSize(mainGameWindowSizeWidth, mainGameWindowSizeHeight);
		mapContaierPan.setStyleName("outerAbsolutePanel");
		
		for(int i=0;i<lenghtOfTileOnYDirection+1;i++){		/*    Y  \ 	*/
			for(int j=0;j<lenghtOfTileOnXDirection+1;j++){ 	/*    X /  	*/
				Image tile=new Image("./brda000.gif");
				map.add(tile);
				map.setWidgetPosition(tile, startX-(j*48),startY+(j*12)  );
			}
			startX+=32;
			startY+=24;
		}
		map.setPixelSize(startX+48, startY+(12*lenghtOfTileOnXDirection)+12);
		
		
		map.setStyleName("innerAbsolutePanel");
		mapContaierPan.add(map);
		focPan = new FocusPanel();			// Place it inside a panel for
		focPan.add(mapContaierPan);					// ...mouse event capture
		focPan.addKeyboardListener(new KeyboardListenerAdapter(){
			public void onKeyPress(Widget sender, char keyCode, int modifiers) {
		        
				String keyPressed = java.lang.Character.toString(keyCode);
				if (keyPressed.equals(" ")){
					for(int i=0;i<view.getContactList().getContactCount();i++){
						if(checkTheHitterPosition(view.getContactList().getContact(i).getName()))
							view.getListener().onHit(view.getContactList().getContact(i));
                    }

					
				}
				
			}
		});
		focPan.addMouseListener(new MouseListenerAdapter()
		{	
			public void onMouseUp(Widget w,int x,int y) {
				
				int[]gridPoint=SetGridPosition(x+mouseOnMapPositionX,y+mouseOnMapPositionY);
				
				view.getContactList().getMe().gridx=gridPoint[0];
				view.getContactList().getMe().gridy=gridPoint[1];
				view.getListener().onChangeLocation(gridPoint[0], gridPoint[1]);
				
			}
			public void onMouseMove(Widget w,int x,int y){

				
				int[]gridPoint=SetGridPosition(x+mouseOnMapPositionX,y+mouseOnMapPositionY);
				map.setWidgetPosition(grid, ((gridPoint[0]*32)-(gridPoint[1]*16)),(gridPoint[1]*12));
				
				if(x>mainGameWindowSizeWidth-40 ){
					mapMoveRight=true;
				}
				if(x<mainGameWindowSizeWidth-40 || x>mainGameWindowSizeWidth-10){
					mapMoveRight=false;
				}
				
				if(x<40 ){
					mapMoveLeft=true;
				}
				if(x>40 || x<10){	
					mapMoveLeft=false;
				}

				if(y>mainGameWindowSizeHeight-40 ){
					mapMoveDown=true;
				}
				if(y<mainGameWindowSizeHeight-40 || y>mainGameWindowSizeHeight-10){
					mapMoveDown=false;
				}
				
				if(y<40){
					mapMoveUp=true;
				}
				if(y>40 || y<10){
					mapMoveUp=false;
				}
			}
		
		});
		
		grid=new Image("./MSEF000.gif");
		map.add(grid);
		map.setWidgetPosition(grid, 0, 0);
		new MapTimer().scheduleRepeating(1); // Start anim loop
		
		/*final TextBox tb=new TextBox();
		RootPanel.get("btn22").add(tb);
		
		Button hitButton = new Button("hit anim",
                new ClickListener() {
                    public void onClick(Widget widget) {
                    	
                    	view.getListener().onHit(view.contactList.getContact(tb.getText()));

                    }
                });
        RootPanel.get("btn").add(hitButton);*/
        
		/*Button dmgButton = new Button("getDMG",
                new ClickListener() {
                    public void onClick(Widget widget) {
                        allCharacters.get(tb.getText()).getDamage();
                    }
                });
        RootPanel.get("btn").add(dmgButton);*/
        
				
		addCharacter( view.getContactList().getMe());
		setWidget(focPan);
	}

	@SuppressWarnings("deprecation")
	public void addCharacter( final Contact contact ){
		int row=view.getContactList().getContactCount();
		if (row !=0){
			
			Character character=(Character)allCharacters.get(contact.getName());
			if(character==null){
				character=new Character(contact,map,view);
				allCharacters.put(contact.getName(), character);
			}
			
		}else{
			Character character=(Character)allCharacters.get(view.getContactList().getMe().getName());
			if(character==null){
				character=new Character(view.getContactList().getMe(),map,view);
				allCharacters.put(contact.getName(), character);
			}			
		}
	}
	
	public void removeCharacter( Contact contact ){

		allCharacters.get(contact.getName()).characterImage.removeFromParent();
		allCharacters.get(contact.getName()).charTimer.cancel();
		allCharacters.get(contact.getName()).nameLbl.removeFromParent();
		allCharacters.remove(contact.getName());
	}
	

	
	private class MapTimer extends Timer/*for map moving*/
	{	public void run()
		{	
			if(mapMoveRight && mapPositionX>-(startX+48-mainGameWindowSizeWidth)){
				mapPositionX-=10;
				mouseOnMapPositionX+=10;
				mapContaierPan.setWidgetPosition(map, mapPositionX, mapPositionY);
			}
			if(mapMoveLeft && mapPositionX<0) {
				mapPositionX+=10;
				mouseOnMapPositionX-=10;
				mapContaierPan.setWidgetPosition(map, mapPositionX, mapPositionY);
			}
			if(mapMoveDown && mapPositionY>-(startY+(12*lenghtOfTileOnXDirection)+12-mainGameWindowSizeHeight)){
				mapPositionY-=10;
				mouseOnMapPositionY+=10;
				mapContaierPan.setWidgetPosition(map, mapPositionX, mapPositionY);
			}
			if(mapMoveUp && mapPositionY<0){
				mapPositionY+=10;
				mouseOnMapPositionY-=10;
				mapContaierPan.setWidgetPosition(map, mapPositionX, mapPositionY);
			}
			
		}
	}
	public static int[] SetGridPosition(int mx, int my) { /*get the grid's numbers of the mouse position*/
		//referance : http://weblogs.java.net/blog/malenkov/archive/2009/02/hexagonal_tile_1.html
		int H=12;
		int R=16;
		int W=32;
		int L=4;
		int j = (int) (my / H);
		int x = mx + ( j * R);
		int i = (int) (x / W);

		my -= (double) j * H;
		if (my < L) {
			x -= (double) i * W + R;
			x *= L / R;
			if (my < Math.abs(x)) {
				j--;
				if (x < 0.0) {
					i--;
				}
			}
		}


		int [] a={i,j};
		return a;
	}
	
	public boolean checkTheHitterPosition(String nameOfHitter){
		
		int hitterX=allCharacters.get(nameOfHitter).charOngridX;
		int hitterY=allCharacters.get(nameOfHitter).charOngridX;
		
		int receiverX=allCharacters.get(view.getContactList().getMe().getName()).charOngridX;
		int receiverY=allCharacters.get(view.getContactList().getMe().getName()).charOngridX;
		
		
		if(hitterX==receiverX && hitterY==(receiverY-1)){
			return true;
		}
		else if(hitterX==(receiverX-1) && hitterY==(receiverY-1)){
			return true;
		}
		else if(hitterX==(receiverX-1) && hitterY==receiverY){
			return true;
		}
		else if(hitterX==(receiverX+1) && hitterY==receiverY){
			return true;
		}
		else if(hitterX==receiverX && hitterY==(receiverY+1)){
			return true;
		}
		else if(hitterX==(receiverX+1) && hitterY==(receiverY+1)){
			return true;
		}
		else if(hitterX==receiverX && hitterY==receiverY){
			return true;
		}
		
		return false;
	}
}
